const Mock = require("mockjs");
const bodyParser = require('body-parser');
const users = require("../dongtluyou/src/user/user.json")
const fs = require("fs")
const data = Mock.mock({
    "list|10":[
        {
            "title":"@cword(10,20)",
            "id":"@id",
             "children|5":[
                 {
                    "title":"@cword(10,20)",
                     "img":"@Image(100x100,@color)"
                 }
             ]
        }
    ]
})
module.exports = {
    devServer:{
        before(app){
            app.get("/list",(req,res)=>{
                res.send(data.list)
            })
            // z这个包是用来解析post请求的
            app.use(bodyParser.json())
            // 登陆接口
            app.post("/login",(req,res)=>{
                let {username,password} = req.body
                let newArr =  users.filter((item,index)=>{
                    return item.username == username
                })
                // newArr.length>0 说明json里有这个数据，继续往里判断，去判断密码对不对
                if (newArr.length) {
                    if (  newArr[0].password == password ) {
                        res.send({
                            code:1,
                            msg:"可以登陆"
                        })
                    } else {
                        res.send({
                            code:0,
                            msg:"账户密码错误"
                        })
                    }
                   
                } else {
                    res.send({
                        code:2,
                        msg:"请您注册"
                    })
                }
              
            })
            // 注册接口
            app.post("/zhuce",(req,res)=>{
                let {username,password} = req.body
                let newArr =  users.filter((item,index)=>{
                     return item.username == username
                 })
                // 如果过滤吕出有结果，说明他注册过，如果length为0 把他写在json里
                if (newArr.length) {
                    res.send({
                        code:0,
                        msg:"您已注册，请登陆"
                    })
                } else {
                    // 把数组psuh
                    users.push({
                        username,
                        password
                    })
                    fs.writeFileSync("./src/user/user.json",JSON.stringify(users))
                    res.send({
                        code:1,
                        msg:"注册成功"
                    })
                }

            })
        }
    }
}
 